<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="categoryId">
        <el-cascader :options="categoryOptions" ref="categoryCascader"
          :props="{ checkStrictly: true, label: 'name', value: 'id', children: 'childCategoryList' }" clearable
          @change="handleChange" style="width: 300px" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <ImagePreview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryName">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.categoryName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="保质期" align="center" prop="shelfLife">
        <template slot-scope="scope">
          {{ scope.row.shelfLife + scope.row.unitString }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改物品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="cancel"
      :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类id" prop="categoryId">
          <el-cascader ref="categoryCascader" :options="categoryOptions" :value="form.categoryId" style="width: 380px;"
            :props="{ label: 'name', value: 'id', children: 'childCategoryList' }" clearable @change="handleChange" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="保质期" prop="shelfLife">
              <el-input-number v-model="form.shelfLife" :precision="0" :min="1" style="width: 150px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位">
                <el-option v-for="item in unitOptions" :key="item.key" :label="item.label" :value="item.key" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="title == '添加物品'">
          <el-col :span="12">
            <el-form-item label="原价" prop="price">
              <el-input-number v-model="form.price" :precision="2" :step="1" :min="0"
                style="width: 150px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买价格" prop="purchasePrice">
              <el-input-number v-model="form.purchasePrice" :precision="2" :step="1" :min="0"
                style="width: 150px"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="title == '添加物品'">
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity" v-if="title == '添加物品'">
              <el-input-number v-model="form.quantity" :precision="0" :min="1" style="width: 150px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重量" prop="weight">
              <el-input v-model="form.weight" clearable placeholder="请输入重量" style="width: 150px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="生产日期" prop="productDate" v-if="title == '添加物品'">
          <el-date-picker clearable v-model="form.productDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图片">
          <image-upload @input="handleImageUpload" :limit="1" :image="form.image" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/item"
import { tree } from "@/api/category"
import ImagePreview from "@/components/ImagePreview"
import Pagination from "@/components/Pagination"
import ImageUpload from "@/components/ImageUpload"

export default {
  name: "Item",
  components: {
    ImagePreview,
    Pagination,
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物品表格数据
      itemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        totalRow: -1,
        categoryId: null,
        name: null,
        shelfLife: null,
        unit: null,
      },
      // 分类选择框
      categoryOptions: [],
      unitOptions: [{ label: '年', key: 1 }, { label: '月', key: 2 }, { label: '日', key: 3 }],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "分类id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        shelfLife: [
          { required: true, message: "保质期不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getTree()
    this.getList()
  },
  methods: {
    /** 查询分类列表 */
    getTree() {
      tree().then(response => {
        this.categoryOptions = response.data
      })
    },
    /** 查询物品列表 */
    getList() {
      this.loading = true
      listItem(this.queryParams).then(response => {
        this.itemList = response.data.records
        this.total = response.data.totalRow
        this.queryParams.totalRow = response.data.totalRow
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      this.handleChange()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        name: null,
        shelfLife: null,
        unit: null,
        // 添加时才会有价格 数量 生产日期
        price: 0,
        purchasePrice: 0,
        quantity: 0,
        weight: null,
        productDate: null,
        image: null,
        createTime: null,
        updateTime: null
      }
      // this.resetForm("form")
      this.$refs.categoryCascader.$refs.panel.checkedValue = []
      this.$refs.categoryCascader.$refs.panel.activePath = []
    },
    /** 树形菜单按钮 */
    handleChange(value) {
      if (value != null && value.length > 0) {
        this.queryParams.categoryId = value[value.length - 1]
        this.form.categoryId = value[value.length - 1]
      } else {
        this.queryParams.categoryId = null
        this.form.categoryId = null
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.totalRow = -1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.$refs.categoryCascader.$refs.panel.checkedValue = []
      this.$refs.categoryCascader.$refs.panel.activePath = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物品"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      getItem(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改物品"
      })
    },
    handleImageUpload(url) {
      this.form.image = url
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.queryParams.categoryId = null;
          if (this.form.id != null) {
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const names = row.name || this.names
      this.$modal.confirm('是否确认删除物品名称为"' + names + '"的数据？').then(function () {
        return delItem(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('flex/item/export', {
    //     ...this.queryParams
    //   }, `item_${new Date().getTime()}.xlsx`)
    // }
  }
}
</script>
